package controllers

import (
	"gitee.com/igolang/imoney/internal/app/system/services"
	"gitee.com/igolang/imoney/internal/common/httpResp"
	"gitee.com/igolang/imoney/internal/models/dao"
	"gitee.com/igolang/pkg/xgorm"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

var Menu = &menu{}

type menu struct{}

func (c *menu) Routers(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Menu.Routers(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *menu) List(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Menu.List(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *menu) Detail(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	id := cast.ToInt64(ctx.Param("id"))
	if id == 0 {
		httpResp.ErrorResponse(httpResp.ErrCodeInvalidParams, r)
		return
	}
	row, err := dao.SysMenu.Where(dao.SysMenu.MenuID.Eq(id)).Take()
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	data := xgorm.ModelToMapWithTag(row, "json")
	data["isCache"] = cast.ToString(row.IsCache)
	data["isFrame"] = cast.ToString(row.IsFrame)
	r.Data = data
}

func (c *menu) Save(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Menu.Save(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *menu) Delete(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	if err := services.Menu.Delete(ctx); err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
}

func (c *menu) Tree(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Menu.Tree(ctx, "")
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}

func (c *menu) RoleMenu(ctx *gin.Context) {
	r := httpResp.Response()
	defer httpResp.JSON(ctx, r)
	data, err := services.Menu.RoleTree(ctx)
	if err != nil {
		httpResp.ErrorResponse(err, r)
		return
	}
	r.Data = data
}
